package com.group.flagtivities;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class FriendSearch extends Activity implements OnClickListener, TextWatcher {
	private static EditText searchCriteria;
	private static LinearLayout searchResults;
	
	private ArrayList<FriendObject> results;
	private Timer t;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_search);
		
		findViews();
		configure();
		
		TextUtil.setFont((ViewGroup) findViewById(R.id.search), getAssets());
	}
	
	private void findViews() {
		searchResults = (LinearLayout) findViewById(R.id.searchResults);
		searchCriteria = (EditText) findViewById(R.id.searchCriteria);
	}
	
	private void configure() {
		searchCriteria.addTextChangedListener(this);
	}
	
	private void fetchResults(String response) {
		try {
			JSONArray jFriends = new JSONArray(response);
			JSONObject jFriend = null;
			int friend_id;
			String first, last;
			for (int i = 0; i < jFriends.length(); i++) {
				jFriend = jFriends.getJSONObject(i);
				friend_id = Integer.parseInt(jFriend.getString("USER_ID"));
				first = jFriend.getString("FIRST");
				last = jFriend.getString("LAST");
				results.add(new FriendObject(friend_id, first, last, 0));
			}
		}catch (Exception e) {}
	}
	
	private void populateSearchResults() {
		results = new ArrayList<FriendObject>();
		searchResults.removeAllViews();
		
		String criteria = searchCriteria.getText().toString().trim();
		
		if (!criteria.isEmpty()) {
			fetchResults(WebUtil.searchFriends(criteria));
			
			for (FriendObject friend : results) {
				createResult(friend);
			}
			
			if (results.size() == 0) {
				TextView view = ViewUtil.generateDefaultTextView(this, "No Friends found.");
				view.setGravity(Gravity.CENTER);
				searchResults.addView(view);
			}
		}
	}

	private boolean isContained(ArrayList<FriendObject> friends, int friend_id) {
		for (FriendObject friend : friends) {
			if (friend.friend_id == friend_id) return true;
		}
		
		return false;
	}
	
	private void configureProfilePicture(TextView view, int friend_id) {
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
        ImageUtil.download("http://flagtivities.netau.net/profile_pics/" + friend_id + ".jpg", view, metrics);
	}
	
	private void configureAction(RelativeLayout r, final FriendObject friend) {
		if (friend.friend_id != Flagtivities.user_id && !isContained(Flagtivities.FriendList, friend.friend_id) && !isContained(Flagtivities.FriendRequestList, friend.friend_id) && !isContained(Flagtivities.FriendPendingList, friend.friend_id)) {
			ImageView action = ViewUtil.generateDefaultImageView(this, getResources().getDrawable(R.drawable.friend_add));
					
			action.setClickable(true);
			action.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					v.setVisibility(View.GONE);
					Flagtivities.FriendPendingList.add(friend);
					WebUtil.requestFriend(Flagtivities.user_id, friend.friend_id);
				}
			});

			r.addView(action);
		}
	}
	
	private void createResult(final FriendObject friend) {
		RelativeLayout r = ViewUtil.generateDefaultRelativeLayout(this, getResources().getDrawable(R.drawable.background_recent));
		TextView v = ViewUtil.generateDefaultTextView(this, friend.first + " " + friend.last);
		configureProfilePicture(v, friend.friend_id);
		
		r.addView(v);
		configureAction(r, friend);
		searchResults.addView(r);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.close:
			finish();
			break;
		}
	}

	@Override
	public void afterTextChanged(Editable s) {}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (searchCriteria.getText().toString().trim().isEmpty()) {
			searchResults.removeAllViews();
			return;
		}
		
		if (t != null) t.cancel();
		t = new Timer();
		t.schedule(new TimerTask() {
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						populateSearchResults();
					}
				});
			}
		}, 1000);
	}
	
}
